// --------------------------------------------------------------------------------------------------------------------
// <copyright file="URDataByteOperations.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.UniversalRobots
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    /// <summary>
    /// Operations for working with byte streams returned by UR controller server.
    /// </summary>
    internal static class URDataByteOperations
    {
        /// <summary>
        /// Minimum size of a packet from URServer interface
        /// </summary>
        private const int MinURServerPacketSize = 10;

        /// <summary>
        /// Maximum size of a packet from URServer interface
        /// </summary>
        private const int MaxURServerPacketSize = 2048;

        /// <summary>
        /// Blits the byte array in <c>sourceByteArray</c> to the structure pointed at by <c>destinationStructPtr</c>
        /// </summary>
        /// <param name="destinationStructPtr">Pointer to the destination array.  Must be pinned.</param>
        /// <param name="sourceByteArray">Array of bytes to blit to the destination array.</param>
        /// <param name="length">Number of bytes to blit.</param>
        /// <param name="sourceIndex">Index to start copying from in source array</param>
        public static unsafe void CopyByteArrayToStructPointer(
            void* destinationStructPtr, 
            byte[] sourceByteArray, 
            int length, 
            int sourceIndex = 0)
        {
            if (sourceByteArray.Length - sourceIndex < length)
            {
                throw new ArgumentException("sourceByteArray must have at least as many bytes after sourceIndex as specified in length");
            }

            byte* structPtr = (byte*)destinationStructPtr;
            for (int i = 0; i < length; ++i)
            {
                structPtr[i] = sourceByteArray[length - i - 1 + sourceIndex];
            }
        }

        /// <summary>
        /// Get the type of and offset to the next package payload in a URServer packet.
        /// </summary>
        /// <param name="buf">Buffer containing the packet.</param>
        /// <param name="currentOffset">Current offset.</param>
        /// <param name="packetSize">Length of the packet.</param>
        /// <returns>A tuple containing the package type and offset.</returns>
        public static Tuple<URDataPackages.PackageTypes, int> GetNextTypeAndOffset(byte[] buf, int currentOffset, int packetSize)
        {
            if (currentOffset == 0)
            {
                // special case
                return new Tuple<URDataPackages.PackageTypes, int>((URDataPackages.PackageTypes)buf[9], 10);
            }
            else
            {
                int nextOffset =
                    currentOffset
                    + URDataPackages.PayloadSizes[(URDataPackages.PackageTypes)buf[currentOffset - 1]]
                    + URDataPackages.HeaderSize;

                if (nextOffset > packetSize ||
                    nextOffset + URDataPackages.PayloadSizes[(URDataPackages.PackageTypes)buf[nextOffset - 1]] > packetSize)
                {
                    return null;
                }

                return new Tuple<URDataPackages.PackageTypes, int>((URDataPackages.PackageTypes)buf[nextOffset - 1], nextOffset);
            }
        }

        /// <summary>
        /// Detects the offsets of packet start locations in a URControl server message.
        /// </summary>
        /// <param name="buf">Buffer containing one or more packets.</param>
        /// <param name="length">Length of buffer.</param>
        /// <returns>Array of packet start locations in the given buffer.</returns>
        public static int[] GetPacketStartOffsets(byte[] buf, int length)
        {
            List<int> startLocations  = new List<int>();

            startLocations.Add(0);
            int currentIndex = 0;

            while (true)
            {
                int size;
                unsafe
                {
                    byte* sizePtr = (byte*)&size;
                    for (int i = 0; i < 4; ++i)
                    {
                        sizePtr[i] = buf[currentIndex + 3 - i];
                    }
                }

                // indicates invalid data
                if (size < MinURServerPacketSize || size > MaxURServerPacketSize)
                {
                    return null;
                }

                currentIndex += size;

                if (currentIndex > length)
                {
                    // indicates an error
                    return null;
                }

                if (currentIndex == length || currentIndex < 0)
                {
                    break;
                }

                startLocations.Add(currentIndex);
            }

            return startLocations.ToArray();
        }
    }
}
